package com.example.mapping.utils;

import com.example.mapping.common.exception.MappingBizException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * jackson工具类
 *
 * @author baoyoujia
 * @date 2022/10/17
 */
@Slf4j
public class JacksonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static ObjectNode parseObjectNode(String json) throws MappingBizException {
        try {
            return MAPPER.readValue(json, ObjectNode.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new MappingBizException("JSON 解析异常");
        }
    }

    public static <T> T parseObject(String str, Class<T> clazz) {
        try {
            return StringUtils.isEmpty(str) ? clazz.newInstance() : MAPPER.readValue(str, clazz);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static String toJSONString(Object obj) {
        if (obj == null) {
            return "";
        }
        if (obj instanceof JsonNode) {
            return obj.toString();
        }

        return toJSONString(obj, false);
    }

    public static String toJSONString(Object obj, boolean format) {
        try {
            if (obj == null) {
                return "";
            }
            if (obj instanceof String || obj instanceof Number) {
                return obj.toString();
            }
            if (format) {
                return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            }
            return MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
